﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using Newtonsoft.Json;
using Pyramid.Bll;
using Pyramid.Models;
using Pyramid.Tools;
using System.Data.Entity;

namespace Pyramid.Controllers
{
	public class HomeController : BaseController
	{
		public ActionResult Index()
		{
			if (User == null)
			{
				return RedirectToAction("Login");
			}
			var account = Db.Accounts.Include(x => x.Roles).Single(x => x.UserId == User.UserId);
			var accountWebObjects = new List<WebObject>();
			if (account.UserTypeEnum == UserTypes.Developer)
			{
				accountWebObjects = Db.WebObjects.ToList();
			}
			else if (account.Roles != null && account.Roles.Count > 0)
			{
				var webIds = account.Roles.SelectMany(x => JsonConvert.DeserializeObject<List<string>>(x.FunctionCodes)).Distinct();
				accountWebObjects = Db.WebObjects.ToList().Where(x => webIds.Contains(x.Id)).ToList();
			}
			var model = new AppViewModel {UserId = User.UserId, UserName = User.FullName, WebObjects = accountWebObjects};
			return View(model);
		}

		[AllowAnonymous]
		public ActionResult Login()
		{
			return View("_Index");
		}

		[HttpPost]
		[AllowAnonymous]
		[ValidateAntiForgeryToken]
		public ActionResult Login(LoginModel model)
		{
			if (string.IsNullOrWhiteSpace(model.UserId)|| string.IsNullOrWhiteSpace(model.Password))
			{
				ModelState.AddModelError("", "请输入用户名和密码！");
				return View("_Index");
			}

			var account = Db.Accounts.SingleOrDefault(x => x.UserId == model.UserId);
			var password = Password.Encryption(model.Password);
			if (account == null || password != account.Password)
			{
				ModelState.AddModelError("", "用户名或密码错误，请重新输入！");
				return View("_Index");
			}

			AccountHelper.NewInstance.LoginAction(account, model.RememberMe, Response);
			return RedirectToAction("Index");
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		public ActionResult LogOff()
		{
			FormsAuthentication.SignOut();
			return RedirectToAction("Login");
		}

		public ActionResult ChangePassword()
		{
			var model = new ChangePasswordModel();
			return View(model);
		}

		[HttpPost]
		public ActionResult ChangePassword(ChangePasswordModel model)
		{
			var account = Db.Accounts.FirstOrDefault(x => x.UserId == User.UserId);
			if (account == null)
			{
				return JTimeOut();
			}

			if (account.Password != Password.Encryption(model.OrignalPassword))
			{
				return JError("旧密码错误，请重新输入！");
			}

			if (model.NewPassword != model.ConfirmPassword)
			{
				return JError("新密码两次输入不一致，请重新输入！");
			}

			account.Password = Password.Encryption(model.NewPassword);
			Db.SaveChanges();
			return JSuccess("密码修改成功，下次登录请用新密码！");
		}
	}
}